/* * File:   main.c
 * Author: juanjo
 *
 * Created on 8 de febrero de 2007, 21:55
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "definiciones.h"
#include "mostrar.c"
/*
 * 
 */

int add_contact(struct nodoamigo** p_agenda)
{
	struct nodoamigo* aux;
	struct nodoamigo* aux2;
	struct nodoamigo tmp;
	char ret;
	printf("\n");
	printf("Enter name:");
	scanf("%s", tmp.name);
	printf("Enter age:");
	scanf("%d", &tmp.age);
	scanf("%c", &ret);
	printf("Enter tel:");
	scanf("%s", tmp.tel);

	if ((*p_agenda) == NULL){ /* What p_agenda points to (agenda) == NULL */
		/* List is EMPTY */
		*p_agenda = (struct nodoamigo *) malloc(sizeof(struct nodoamigo)); /*Assigns memory to agenda*/
		aux = *p_agenda;
		*aux = tmp;
		aux->sig = NULL;
	}
	else {
		/*There's something in the list */
		aux = *p_agenda; /*aux points to agenda*/
		if (strcmp(aux->name, tmp.name) > 0){ /*Returns > 0 if s1 is greater than s2 */
			aux2 = aux; 
			*p_agenda = (struct nodoamigo *) malloc(sizeof(struct nodoamigo));/*Assigns memory to agenda*/
			(**p_agenda) = tmp; /*Assigns tmp to the struct which agenda points to */
			(**p_agenda).sig = aux2; /*Could be (*p_agenda)->sig = aux2 */
		}
		else {
			while (aux->sig != NULL && (strcmp((*aux).name, tmp.name) < 0)){ 
				aux = aux->sig;  /* Looking for ->sig = NULL and s1 less than s2*/ 
			}
			/*Now aux points to the node that is just before the one
			 * we want to insert. */
			aux2 = (struct nodoamigo *) malloc(sizeof(struct nodoamigo)); /*Assigns memory to aux2 struct*/
			*aux2 = tmp; /*Copies data (tmp) to aux2 struct */
			aux2->sig = aux->sig; /*aux2 now points to the next struct*/
			aux->sig = aux2; /* aux points to aux2 */
	}
	return 0;
}

int main(int argc, char** argv) {
	struct nodoamigo *agenda;
    
	agenda = NULL;
	add_contact(&agenda);
	add_contact(&agenda);
	add_contact(&agenda);
	mostrar(agenda);
	return (EXIT_SUCCESS);
}
